﻿/****************************************************
 * 
 * 
 * ---------------------------------------------------------------------------
 * |ID                    |Type           |Description                       |
 * +----------------------+---------------+----------------------------------+
 * |Password              |ITextControl   |Old password                      |
 * +----------------------+---------------+----------------------------------+
 * |NewPassword           |ITextControl   |New password                      |
 * +----------------------+---------------+----------------------------------+
 * |NewPassword2          |ITextControl   |New password again                |
 * +----------------------+---------------+----------------------------------+
 * |(Any)                 |IButtonControl |Submit button.                    |
 * |                      |               |CommandName = "Submit"            |
 * -----------------------+---------------+-----------------------------------
 * 
 * 
 ****************************************************/
using System;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyLib.Web.Pages {
	/// <summary>
	/// 
	/// </summary>
	public abstract class ChangePasswordPage : MyPage {
		/// <summary>
		/// 
		/// </summary>
		/// <param name="e"></param>
		protected override void OnLoad(EventArgs e) {
			base.OnLoad(e);

			Title = Properties.Main.TitleChangePassword;

			if (!IsPostBack) {
				var passwordCtrl = Form.FindDescendantControl<Control>("Password") as ITextControl;
				var newPasswordCtrl = Form.FindDescendantControl<Control>("NewPassword") as ITextControl;
				var newPasswordCtrl2 = Form.FindDescendantControl<Control>("NewPassword2") as ITextControl;

				var cp = RetrievePassword(User.Identity.Name);
				var cpRow = cp[0];
				if (passwordCtrl != null) {
					passwordCtrl.Text = cpRow.Password;
				}
				if (newPasswordCtrl != null) {
					newPasswordCtrl.Text = cpRow.NewPassword;
				}
				if (newPasswordCtrl2 != null) {
					newPasswordCtrl2.Text = cpRow.NewPassword;
				}
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="source"></param>
		/// <param name="args"></param>
		/// <returns></returns>
		protected override bool OnBubbleEvent(object source, EventArgs args) {
			bool causesValidation = false;
			string validationGroup = string.Empty;

			if (args is CommandEventArgs) {
				IButtonControl commandSource = source as IButtonControl;
				if (commandSource != null) {
					causesValidation = commandSource.CausesValidation;
					validationGroup = commandSource.ValidationGroup;
				}

				var cargs = (CommandEventArgs)args;

				if (string.Equals(cargs.CommandName, "Submit", StringComparison.OrdinalIgnoreCase)) {
					HandleSubmit(causesValidation, validationGroup);
					return true;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="causesValidation"></param>
		/// <param name="validationGroup"></param>
		private void HandleSubmit(bool causesValidation, string validationGroup) {
			if (!causesValidation || this.IsValid) {
				var password = string.Empty; // Default value.
				var newPassword = string.Empty;
				var newPassword2 = string.Empty;

				var passwordCtrl = Form.FindDescendantControl<TextBox>("Password");
				var newPasswordCtrl = Form.FindDescendantControl<TextBox>("NewPassword");
				var newPasswordCtrl2 = Form.FindDescendantControl<TextBox>("NewPassword2");

				if (passwordCtrl != null) {
					password = passwordCtrl.Text.Trim();
				}
				if (newPasswordCtrl != null) {
					newPassword = newPasswordCtrl.Text.Trim();
				}
				if (newPasswordCtrl2 != null) {
					newPassword2 = newPasswordCtrl2.Text.Trim();
				}

				if (newPassword != newPassword2) {
					Context.AddError(Properties.Main.ErrorNewPasswordNotMatch);
					return;
				}

				Context.ExecuteSafely(() => {
					ChangeUserPassword(User.Identity.Name, password, newPassword);

					OnPasswordChanged(this, EventArgs.Empty);
				});
			} // end of if.
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="userId"></param>
		/// <returns></returns>
		protected virtual MyLib.Data.ChangePasswordTable RetrievePassword(string userId) {
			var ap = GetDbProvider<MyLib.Data.AuthorityProvider>();

			return ap.RetrievePassword(userId);
		}

		/// <summary>
		/// Change password.
		/// </summary>
		/// <param name="userId"></param>
		/// <param name="password"></param>
		/// <param name="newPassword"></param>
		protected virtual void ChangeUserPassword(string userId, string password, string newPassword) {
			var ap = GetDbProvider<MyLib.Data.AuthorityProvider>();

			ap.ChangePassword(userId, password, newPassword);
		}

		/// <summary>
		/// 
		/// </summary>
		protected virtual void OnPasswordChanged(object source, EventArgs args) {
		}
	} // end of LoginPage.
}
